# -*- coding: utf-8 -*-

from pymongo import UpdateOne, DESCENDING
from factor.base_factor import BaseFactor
from data.finance_report_crawler import FinanceReportCrawler
from data.data_module import DataModule
from util.stock_util import get_all_codes, get_trading_dates
from util.database import DB_CONN
import pandas as pd
import numpy as np
from util.erio_util import dualdate, dualdateb, dual_ammount, dualcode, dualbasicdate

"""
实现市盈率因子的计算和保存
"""


class SP_TTM_Factor(BaseFactor):
    def __init__(self):
        BaseFactor.__init__(self, name='pe')

    def compute(self, begin_date, end_date):
        """
        计算指定时间段内所有股票的该因子的值，并保存到数据库中
        :param begin_date:  开始时间
        :param end_date: 结束时间
        """
        dm = DataModule()
        dates = get_trading_dates(begin_date, end_date)
        codes = ['601808']
        update_requests = []
        for code in codes:
            data = dm.get_stock_lrb(code)
            basicdata = dm.get_stock_basic(dualcode(code))

            zcfcall = dm.get_stock_zcfzb(code)
            xjlball = dm.get_stock_xjllb(code)
            lrall = dm.get_stock_lrb(code)

            for date in dates:
                for asa in data['report_date'].apply(dualdate):
                    if date < asa:
                        continue
                    else:
                        reportdat = asa
                        break
                TTM = basicdata[basicdata['trade_date'] == dualbasicdate(date)]['total_mv'].tolist()[0] * 10000
                net_profit = \
                    lrall[lrall['report_date'] ==  dualdateb(reportdat)]['NETPROFIT'].apply(dual_ammount).astype('float').tolist()[0]
                amortization = \
                zcfcall[zcfcall['report_date'] == dualdateb(reportdat)]['LTDEFERASSET'].apply(dual_ammount).astype(
                    'float').tolist()[0]
                depreciation = \
                lrall[lrall['report_date'] == dualdateb(reportdat)]['ASSETDEVALUELOSS'].apply(dual_ammount).astype(
                    'float').tolist()[0]
                capital_expenditures = \
                xjlball[xjlball['report_date'] == dualdateb(reportdat)]['BUYFILASSETPAY'].apply(dual_ammount).astype(
                    'float').tolist()[0]

                # print (net_profit,amortization,net_profit,capital_expenditures)
                # net_profit = dm.get_stock_mainreport(code, reportdat)['yyzsr'].apply(dual_ammount).astype('float')
                # amortization = dm.get_stock_zcfzb(code, dualdateb(reportdat))['LTDEFERASSET'].astype('float')
                # depreciation = dm.get_stock_lrb(code, dualdateb(reportdat))['ASSETDEVALUELOSS'].astype('float')
                # capital_expenditures = dm.get_stock_xjllb(code, dualdateb(reportdat))['BUYFILASSETPAY'].astype('float')
                # working_capital = dm.get_stock_zcfzb(code, dualdateb(reportdat))['SUMLASSET'].astype('float') - \
                #                   dm.get_stock_zcfzb(code, dualdateb(reportdat))['SUMLLIAB'].astype('float')

                working_capital = zcfcall[zcfcall['report_date'] ==  dualdateb(reportdat)]['SUMLASSET'].astype('float') - \
                                  zcfcall[zcfcall['report_date'] ==  dualdateb(reportdat)]['SUMLLIAB'].astype('float')
                FCFP = net_profit + amortization + depreciation - capital_expenditures - working_capital
                print  (int(FCFP))
                FCFP_TTM = (FCFP / TTM)
                update_requests.append(
                    UpdateOne(
                        {'code': code, 'date': date},
                        {'$set': {'code': code, 'date': date, 'FCFP_TTM': FCFP_TTM}}, upsert=True))
                print(update_requests)
                break
            break


SP_TTM_Factor().compute('2018-01-02', '2018-09-05')
